package com.example.linearlayoutdemo.networkstate;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.util.Log;
import android.widget.Toast;

import com.example.linearlayoutdemo.HomeActivity;

public class NetworkMonitor {
    private static final String TAG = "FixedNetworkMonitor";
    private Context context;
    private ConnectivityManager connectivityManager;
    private NetworkCallback networkCallback;
    private boolean isNetworkAvailable;

    public NetworkMonitor(Context context) {
        this.context = context;
        this.connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        this.isNetworkAvailable = checkInitialNetworkState(); // 初始状态判断
    }

    /**
     * 开始监听（关键：监听所有可能的网络类型）
     */
    public void startMonitoring() {
        if (connectivityManager == null) {
            Log.e(TAG, "无法获取ConnectivityManager");
            return;
        }

        // 1. 构建无限制的NetworkRequest（监听所有网络类型）
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                // 去掉特定网络类型限制，确保所有网络变化都能被监听
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) // 仅保留基础上网能力判断
                .build();

        // 2. 完善的回调实现
        networkCallback = new NetworkCallback();
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
    }

    /**
     * 自定义NetworkCallback，确保断开事件被捕获
     */
    private class NetworkCallback extends ConnectivityManager.NetworkCallback {
        // 网络可用时触发
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            // 仅判断是否具备上网能力（已去掉VALIDATED验证）
            NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
            boolean newState = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);

            if (newState && !isNetworkAvailable) {
                isNetworkAvailable = true;
                showToast("网络已连接");
                Log.d(TAG, "网络连接成功");
            }
        }

        // 网络断开时触发（针对单个网络）
        @Override
        public void onLost(Network network) {
            super.onLost(network);
            // 检查是否还有其他可用网络
            boolean hasOtherNetwork = checkIfAnyNetworkAvailable();
            if (!hasOtherNetwork && isNetworkAvailable) {
                isNetworkAvailable = false;
                showToast("网络已断开");
                Log.d(TAG, "网络断开");
            }
        }

        // 网络完全不可用时触发（如飞行模式）
        @Override
        public void onUnavailable() {
            super.onUnavailable();
            if (isNetworkAvailable) {
                isNetworkAvailable = false;
                showToast("网络不可用");
                Log.d(TAG, "网络完全不可用");
            }
        }
    }

    /**
     * 检查是否存在任何可用网络（解决多网络切换问题）
     */
    private boolean checkIfAnyNetworkAvailable() {
        if (connectivityManager == null) return false;

        // 遍历所有网络，判断是否有可用网络
        for (Network network : connectivityManager.getAllNetworks()) {
            NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
            if (capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始网络状态检查
     */
    private boolean checkInitialNetworkState() {
        if (connectivityManager == null) return false;

        Network activeNetwork = connectivityManager.getActiveNetwork();
        if (activeNetwork == null) return false;

        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
        return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }

    /**
     * 停止监听（必须在Activity销毁时调用）
     */
    public void stopMonitoring() {
        if (connectivityManager != null && networkCallback != null) {
            connectivityManager.unregisterNetworkCallback(networkCallback);
            Log.d(TAG, "已停止网络监听");
        }
    }

    private void showToast(String message) {
        ((HomeActivity) context).runOnUiThread(() ->
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        );
    }

    public boolean isNetworkAvailable() {
        return isNetworkAvailable;
    }
}

